// https://www.lintcode.com/problem/rotate-list/

/**
 * Definition for ListNode
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        if (head == null) {
          return head;
        }
        int len = 0;
        ListNode tail = null;
        ListNode node = head;
        while (node != null) {
          ++len;
          tail = node;
          node = node.next;
        }
        int shift = k % len;
        if (shift == 0) {
          return head;
        }
        node = head;
        for (int i = 0; i < (len - shift - 1); ++i) {
          node = node.next;
        }
        ListNode newHead = node.next;
        tail.next = head;
        node.next = null;
        return newHead;
    }
}